package com.jiyi.activity.supervision;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.weibao.CompanyBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.SupervisionOwnerEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  SupervisionAllOwnerActivity.java   
 * @Package    
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-21 下午1:38:18   
 * @version V1.0     
 */

/**   
 * @ClassName:  SupervisionAllOwnerActivity   
 * @Description:TODO(业务查询-所有业主)   
 * @author: HYM  
 * @date:   2017-10-21 下午1:38:18   
 *      
 */
public class SupervisionBusiAllOwnerActivity extends ActivityBase implements OnRefreshListener{

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.ivPeople)
	ImageView ivPeople;
	@BindView(R.id.ivSearch)
	ImageView ivSearch;
	@BindView(R.id.etSearch)
	ClearEditText etSearch;

	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	ViewGroup container;
	private List<CompanyBean> dataList = new ArrayList<CompanyBean>();
	// 监管大队的id,name,被查看的用户ID
	String supervision_id, supervision_name,user_id;
	//该页面的功能 1 大队长切换的业主列表界面 2 大队长或者参谋查看子角色的列表界面
	int func = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_supervision_busi_all_owner);
		ButterKnife.bind(this);
		init();
	}
	
	private void init() {
		inflater = LayoutInflater.from(this);
		getIntentData();
		setTop();
		initViewState();
		setAdapter();
		getData();
		EventBus.getDefault().register(this);
	}

	@Subscribe
	public void onSupervisionOwnerEvent(
			SupervisionOwnerEvent supervisionOwnerEvent) {
		int func = supervisionOwnerEvent.func;
		switch (func) {
		case 1:
			for (int i = 0; i < dataList.size(); i++) {
				CompanyBean companyBean = dataList.get(i);
				if (companyBean.getId().equals(supervisionOwnerEvent.ownerId)) {
					dataList.remove(i);
					adapter.notifyDataSetChanged();
					break;
				}
			}
			break;
		case 2:
			dataList.addAll(supervisionOwnerEvent.addOwner);
			adapter.notifyDataSetChanged();
			break;

		default:
			break;
		}

	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void getIntentData() {
		func = getIntent().getIntExtra("func", 1);
		user_id = getIntent().getStringExtra("user_id");
	}

	private void setTop() {
		tvTitle.setText("业务查询");
		if (func == 2) {
			ivPeople.setVisibility(View.GONE);
		}
		ivSearch.setVisibility(View.GONE);
	}

	
	private void initViewState() {
		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					getData();
					return true;
				}
				return false;
			}
		});

	}
	
	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(this));
		mListView.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, null));

		CommonAdapter mCommonAdapter = new CommonAdapter<CompanyBean>(this,
				R.layout.item_supervision_owner_add, dataList) {
			@Override
			protected void convert(ViewHolder holder, final CompanyBean t,
					int position) {
				holder.setText(R.id.tvOwnerName, t.getName());
				holder.setText(R.id.tvOwnerPhone, t.getPhone());
				holder.setText(R.id.tvOwnerAddress, t.getAddress());

				holder.setImage(R.id.ivLogo, t.getCompany_logo() == null ? ""
						: t.getCompany_logo());
				holder.setOnClickListener(R.id.rlRoot, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),SupervisionBusiDetailActivity.class);
						intent.putExtra("owner_id", t.getId());
						startActivity(intent);
					}
				});
			}
		};

		adapter = new EmptyWrapper(mCommonAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				mListView, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onRefresh() {
		getData();
	}

	private void getData() {
		String url;
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(etSearch.getText().toString())) {
			params.put("com_name",etSearch.getText().toString());
		}
		if (func == 2) {
			if (UserInfoUtil.getCurrentUserSupervisionRole() == 3) {
				url = WebApi.SUPERVISION_SELF_UNITS;
			}
			else
			{
				params.put("user_id", user_id);
				url = WebApi.SUPERVISION_BUSI_NEXT_OWNER_LIST;
			}
			
		}
		else {
			if (UserInfoUtil.getCurrentUserSupervisionRole() == 1) {
				url = WebApi.SUPERVISION_BUSI_OWNER_LIST;
			}
			else {
				url = WebApi.SUPERVISION_SELF_UNITS;
			}
		}
		VolleyRequest.StringRequestPost(this,
				url, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<CompanyBean> temp = new Gson().fromJson(
										data,
										new TypeToken<List<CompanyBean>>() {
										}.getType());
								dataList.clear();
								dataList.addAll(temp);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@OnClick({ R.id.tvBack, R.id.ivPeople,R.id.ivSearch })
	public void onClick(View view) {
		Intent intent;
		switch (view.getId()) {
		case R.id.tvBack:
		case R.id.ivPeople:
			finish();
			break;
		
		default:
			break;
		}
	}
}
